package cn.tedu.blog.server.repo.impl;

import cn.tedu.blog.server.pojo.vo.TagDetailVO;
import cn.tedu.blog.server.pojo.vo.TagListItemVO;
import cn.tedu.blog.server.repo.ITagRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
@Slf4j
public class TagRepositoryImpl implements ITagRepository {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void put(TagDetailVO tagDetailVO) {
        String key = KEY_PREFIX_Tag_ITEM + tagDetailVO.getId();
        redisTemplate.opsForValue().set(key, tagDetailVO);
    }

    @Override
    public TagDetailVO get(Long id) {
        TagDetailVO tag = null;
        String key = KEY_PREFIX_Tag_ITEM + id;
        Serializable serializable = redisTemplate.opsForValue().get(key);
        if (serializable != null) {
            if (serializable instanceof TagDetailVO) {
                tag = (TagDetailVO) serializable;
            }
        }
        return tag;
    }

    @Override
    public void putList(List<TagListItemVO> list, String key) {
        log.debug("向Redis中写入标签列表数据:{}",list);
        for (TagListItemVO tagListItemVO : list){
            redisTemplate.opsForList().rightPush(key,tagListItemVO);
        }
        switch (key){
            case KEY_PREFIX_Tag_ITEM:
                redisTemplate.expire(key,1L, TimeUnit.DAYS);
                break;
        }

    }

    @Override
    public List<TagListItemVO> getList(String key) {
        log.debug("即将从Redis中读取标签列表数据...");
        List<Serializable> list = redisTemplate.opsForList().range(key, 0, -1);
        List<TagListItemVO> tagList=new ArrayList<>();
        for (Serializable serializable : list){
            tagList.add((TagListItemVO) serializable);
            log.debug("从Redis中读取到的标签列表:{}",tagList);
        }
        return tagList;
    }

    @Override
    public boolean isExpired(String key) {
        Long expiredTime= redisTemplate.getExpire(key);
        log.debug("密钥有效时间：{}",expiredTime);
        if(expiredTime==-2){
            return true;
        }
        return false;
    }
}
